package com.whjk.safework.controller;

import cn.hutool.core.date.DateUtil;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.whjk.safework.service.IWorkerService;
import com.whjk.safework.utils.LoaclDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: safework
 * @BelongsPackage: com.whjk.safework.controller
 * @Author: leebin
 * @CreateTime: 2024-08-24  17:18
 * @Description: TODO
 * @Version: 1.0
 */

@RestController
@RequestMapping(value = "/test")
public class Test {

    @Autowired
    private IWorkerService workerService;
    @RequestMapping(value="/week",method = RequestMethod.GET)
    public Object week(){

        Row row1=LoaclDateUtil.getThisWeekStartDay("2024-12-31",1);
        Row row2= LoaclDateUtil.getThisWeekStartDay("2025-01-01",1);
        Row row3= LoaclDateUtil.getThisWeekStartDay("2025-01-02",1);
        Row row4= LoaclDateUtil.getThisWeekStartDay("2025-01-03",1);
        Row row5= LoaclDateUtil.getThisWeekStartDay("2025-01-04",1);
        Row row6= LoaclDateUtil.getThisWeekStartDay("2025-01-05",1);

        Row row7= LoaclDateUtil.getThisWeekStartDay(1);

        List<Row> rowList = new ArrayList<>();
        rowList.add(row1);
        rowList.add(row2);
        rowList.add(row3);
        rowList.add(row4);
        rowList.add(row5);
        rowList.add(row6);
        rowList.add(row7);

        return  rowList;
    }
    @RequestMapping(value="/sx",method = RequestMethod.GET)
    public Object sx(){
        List<Row>  workerList   =  Db.selectListBySql("select * from t_worker   where work_status=0 and is_del=0 and user_id IS NOT NULL ");
        for (Row workerRow:workerList) {
            workerService.refreshWorkerScore(workerRow.getInt("id"), DateUtil.year(DateUtil.date()));
        }

        return  "ss";
    }


    @RequestMapping(value="/deptx",method = RequestMethod.GET)
    public Object deptx(){

        String startTime = LoaclDateUtil.getPreMonthFirstDay();
        String endTime   = LoaclDateUtil.getCurrentMonthFirstDay();
        String month     = LoaclDateUtil.getMonth(1,"yyyy-MM");

        List<Row>  orgList   =  Db.selectListBySql("select * from t_org where (level_idx=2 and is_have_child=0 and is_del=0) or (level_idx=3  and is_del=0)");

        for (Row orgRow:orgList) {
            String  worker_sql = "select t_worker.id,t_worker.name from t_worker join t_position on t_worker.position_id= t_position.id join t_org on t_position.dep_id=t_org.id "
                    +"where t_org.path like ? and  work_status=0 and t_worker.is_del=0 and t_worker.user_id IS NOT NULL";
            int workerTargetNum       = 0;
            int workerTargetNum_good  = 0;
            int workerTargetNum_ok    = 0;
            List<Row>  workerList     =  Db.selectListBySql(worker_sql, "%"+orgRow.get("path")+"%");

            for (Row worker:workerList) {
                // 查询任务数
                Row targetNum      = Db.selectOneBySql("select count(*) as num  from t_worker_target where  start_time>= ? and end_time<= ? and worker_id=?", startTime, endTime, worker.getInt("id"));
                Row targetNum_good = Db.selectOneBySql("select count(*) as num  from t_worker_target where  start_time>= ? and end_time<= ? and worker_id=? and   my_check_result>=9",  startTime, endTime,  worker.getInt("id"));
                Row targetNum_ok   = Db.selectOneBySql("select count(*) as num  from t_worker_target where  start_time>= ? and end_time<= ? and worker_id=? and my_check_time IS NOT NULL",  startTime, endTime,  worker.getInt("id"));
                int targetNum_num   =  targetNum.getInt("num");
                int targetNum_good_num   =  targetNum_good.getInt("num");
                int targetNum_ok_num   =  targetNum_ok.getInt("num");

                if(targetNum_num>0){
                    workerTargetNum         =   workerTargetNum+targetNum_num;
                    workerTargetNum_good    =   workerTargetNum_good+targetNum_good_num;
                    workerTargetNum_ok      =   workerTargetNum_ok+targetNum_ok_num;
                }
            }
            if (workerTargetNum>0){
                BigDecimal targetNum_score = new BigDecimal(workerTargetNum_good).divide(new BigDecimal(workerTargetNum),2,BigDecimal.ROUND_HALF_UP); // 优秀
                BigDecimal targetNum_score_ok = new BigDecimal(workerTargetNum_ok).divide(new BigDecimal(workerTargetNum),2,BigDecimal.ROUND_HALF_UP); // 完成

                String path = orgRow.getString("path","");

                if(!path.equals("")){
                    String trimmedInput = path.replaceAll("^/|/$", "");
                    String[] parts = trimmedInput.split("/");

                    if (parts.length>=3) {
                        String depId = parts[2];
                        long count =Db.selectCount("select count(*) from t_dep_lz_num where dep_id=? and month=?",depId,month);
                        if(count==0){
                            Row row = new Row();
                            row.set("dep_id",depId);
                            row.set("org_id",parts[0]);
                            row.set("month",month);
                            row.set("worker_num",workerTargetNum); // 履职总数
                            row.set("finished_num",workerTargetNum_ok); // 完成总数
                            row.set("good_num",workerTargetNum_good); // 优秀总数
                            row.set("finished_pre",targetNum_score_ok);
                            row.set("ok_pre",targetNum_score);
                            Db.insert("t_dep_lz_num",row);
                        }
                        else if(count>0){
                            Row row_old = new Row();
                                row_old.set("dep_id",depId);
                                row_old.set("org_id",parts[0]);
                                row_old.set("month",month);
                            Row row = new Row();
                                row.set("dep_id",depId);
                                row.set("org_id",parts[0]);
                                row.set("month",month);
                                row.set("worker_num",workerTargetNum);
                                row.set("finished_num",workerTargetNum_ok);
                                row.set("good_num",workerTargetNum_good);
                                row.set("finished_pre",targetNum_score_ok);
                                row.set("ok_pre",targetNum_score);
                                row.set("update_time",DateUtil.now());
                            Db.updateByMap("t_dep_lz_num",row,row_old);
                        }
                    }
                }
                System.out.println("计算结果："+orgRow.get("name")+"_"+targetNum_score+"_"+targetNum_score_ok);
            }
        }

        return  "ss";
    }

    @RequestMapping(value="/getMonth",method = RequestMethod.GET)
    public Object getMonth(){

        return      DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -1),"yyyy-MM");
    }


    @RequestMapping(value="/monthTj",method = RequestMethod.GET)
    public Object monthTj(){

        String  startTime    =     LoaclDateUtil.getPreMonthFirstDay();
        String  endTime      =     LoaclDateUtil.getCurrentMonthFirstDay();
        String  month        =     LoaclDateUtil.getMonth(1,"yyyy-MM");

        List<Row>  orgList   =     Db.selectListBySql("select id,name from t_org where pid=0 and is_del=0");


      //  List<Row>  orgList   =     Db.selectListBySql("select * from t_worker_target where   ");

        return "";

    }


    @RequestMapping(value="/workerRecord",method = RequestMethod.GET)
    public Object workerRecord(){
        List<Row>  orgList   = workerService.getWorkerAllRecord(45,"2025-05");
        return orgList;
    }


    @RequestMapping(value="/listmonth",method = RequestMethod.GET)
    public Object listmonth(){

        int currentYear = DateUtil.year(DateUtil.date()); // 获取当前年份
        int currentMonth = DateUtil.month(DateUtil.date()) + 1; // 当前月份（0~11，需+1）

        for (int i = 1; i <= currentMonth; i++) {
            String month = DateUtil.parse(currentYear + "-" + i, "yyyy-M").toString("yyyy-MM");
            List<Row>  workerList   =  Db.selectListBySql("select * from t_worker   where work_status=0 and is_del=0 and user_id IS NOT NULL ");
            for (Row workerRow:workerList) {
                workerService.refreshWorkersMonthSocre(workerRow.getInt("id"), month);    //refreshWorkerScore(workerRow.getInt("id"), DateUtil.year(DateUtil.date()));
            }
        }
        return  "ss";
    }



    @RequestMapping(value="/reworker",method = RequestMethod.GET)
    public String reworker(){
        workerService.refreshWorkersMonthSocre(45, "2025-07");
        return  "ss";
    }

}
